package xin.common.file;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.WebResource;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.security.SecureRandom;

/**
 * <pre>
 * 远程文件上传
 * </pre>
 *
 * @author lixin_ma@outlook.com
 * @version 1.0
 * @since 2018/9/21 0:11
 */
public class RemoteUploader extends AbstractUploader  {

    private SecureRandom secureRandom;
    private Client client;


    public RemoteUploader(){
        secureRandom = new SecureRandom();
        client = new Client();
    }

    @Override
    public void upload(MultipartFile file, HttpServletRequest request, HttpServletResponse response,String serverPath, String path, UploadResult result){

        // 文件名
        String fileName = getFileName(file);
        //相对路径
        String relativePath = path + fileName;

        String a = serverPath + path.substring(0, path.lastIndexOf("/"));
        File dir = new File(a);
        if(!dir.exists()){
            dir.mkdirs();
        }

        //服务器路径
        String realPath = serverPath + relativePath;
        // 设置请求路径
        WebResource resource = client.resource(realPath);

        // 发送开始post get put（基于put提交）
        try {
            resource.put(String.class, file.getBytes());
            result.setSuccess(Boolean.TRUE);
            result.setFileName(fileName);
            result.setRelativePath(relativePath);
            result.setRealPath(realPath);

        } catch (IOException e) {
            e.printStackTrace();
            result.setSuccess(Boolean.FALSE);
        }catch (ClientHandlerException e) {
            e.printStackTrace();
            result.setSuccess(Boolean.FALSE);
        } finally {
            // something
        }
    }


}
